package com.xq.tmall.agu.timer;

import com.alibaba.excel.util.DateUtils;
import com.xq.tmall.entity.StockSector;
import com.xq.tmall.entity.StockSectorHistory;
import com.xq.tmall.service.StockSectorHistoryService;
import com.xq.tmall.service.StockSectorService;
import com.xq.tmall.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class StockSectorHistoryTimer {

    @Autowired
    private StockSectorHistoryService sectorHistoryService;

    @Autowired
    private StockSectorService stockSectorService;

    /**
     * 每天17:20执行板块历史数据更新
     */
    @Scheduled(cron = "0 50 15 * * ?")
    public void dailySectorHistoryUpdate() {
        log.info("开始执行板块历史数据更新任务...");

        try {
            LocalDateTime dateTime = LocalDateTime.now();
            // 周末不执行
            boolean isWeek = DateUtil.isWeekend(dateTime);
            if(isWeek){
                log.info("周末不执行");
                return;
            }
            // 清理90天前的历史数据
            cleanOldHistoryData();

            // 检查当天数据是否已存在
            if (isTodayDataExists()) {
                log.info("今日板块历史数据已存在，跳过任务");
                return;
            }

            // 获取所有板块信息
            List<StockSector> stockSectorList = stockSectorService.findAllStockSectorInfo(new HashMap<>());
            log.info("获取到 {} 个板块信息", stockSectorList.size());

            // 插入历史记录
            if (!CollectionUtils.isEmpty(stockSectorList)) {
                sectorHistoryService.batchInsert(stockSectorList);
                log.info("成功插入 {} 条板块历史数据", stockSectorList.size());
            } else {
                log.warn("未获取到有效的板块信息");
            }
        } catch (Exception e) {
            log.error("板块历史数据更新失败", e);
        }
    }

    private void cleanOldHistoryData() {
        try {
            Date historyDate = DateUtil.addDay(new Date(), -300);
            String deleteDate = DateUtils.format(historyDate, "yyyy-MM-dd");
            sectorHistoryService.historyDelete(deleteDate);
            log.info("已清理 {} 之前的板块历史数据", deleteDate);
        } catch (Exception e) {
            log.error("清理板块历史数据失败", e);
        }
    }

    private boolean isTodayDataExists() {
        Map<String, Object> params = new HashMap<>();
        params.put("historyDate", DateUtils.format(new Date(), "yyyy-MM-dd"));
        List<StockSectorHistory> historyList = sectorHistoryService.findStockSectorHistoryList(params);
        return !CollectionUtils.isEmpty(historyList);
    }
}
